import os
from etcd_config_manager import EtcdConfigManager
from typing import Dict

class EnvConfigSyncer:
    def __init__(self, etcd_manager: EtcdConfigManager):
        self.etcd = etcd_manager
    
    def sync_prefix(self, prefix: str, uppercase: bool = True) -> Dict[str, Any]:
        """同步指定前缀的配置到环境变量"""
        configs = {}
        try:
            # 获取所有指定前缀的键值对
            for value, metadata in self.etcd.client.get_prefix(prefix):
                key = metadata.key.decode('utf-8')
                env_key = key.replace(prefix, '').replace('/', '_')
                if uppercase:
                    env_key = env_key.upper()
                
                try:
                    config_value = json.loads(value.decode('utf-8'))
                except json.JSONDecodeError:
                    config_value = value.decode('utf-8')
                
                os.environ[env_key] = str(config_value)
                configs[env_key] = config_value
            
            print(f"Synced {len(configs)} configs to environment variables")
            return configs
        except Exception as e:
            print(f"Sync failed: {e}")
            return {}

# 使用示例
if __name__ == "__main__":
    etcd_manager = EtcdConfigManager()
    syncer = EnvConfigSyncer(etcd_manager)
    
    # 存储一些测试配置
    etcd_manager.put_config("/env/DATABASE_HOST", "db.example.com")
    etcd_manager.put_config("/env/DATABASE_PORT", "3306")
    etcd_manager.put_config("/env/DEBUG_MODE", "true")
    
    # 同步配置到环境变量
    syncer.sync_prefix("/env/")
    
    # 验证
    print("DATABASE_HOST:", os.getenv("DATABASE_HOST"))
    print("DATABASE_PORT:", os.getenv("DATABASE_PORT"))
    print("DEBUG_MODE:", os.getenv("DEBUG_MODE"))